# -- coding:utf-8 --

from bluetooth import *
from PyQt4 import QtCore

class bluetooth(QtCore.QThread):

    IsConnect = QtCore.pyqtSignal(bool)
    Data = QtCore.pyqtSignal(str, str, int, int)

    def __init__(self, parent = None):
        super(bluetooth, self).__init__(parent)
        self.server_sock = BluetoothSocket(RFCOMM)
        self.server_sock.bind(("",PORT_ANY))
        self.server_sock.listen(1)

        self.port = self.server_sock.getsockname()[1]
        self.uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

        self.ConnectFlag = False

        advertise_service(self.server_sock, "SampleServer",
                          service_id = self.uuid,
                          service_classes = [ self.uuid, SERIAL_PORT_CLASS ],
                          profiles = [ SERIAL_PORT_PROFILE ], 
                        #   protocols = [ OBEX_UUID ] 
                         )
    
    
    def SendData(self, result):
        self.client_sock.send(unicode(result, 'utf-8'))

    def run(self):
        while True:
            if self.ConnectFlag:
                try:
                    while True:
                        data = self.client_sock.recv(1024)
                        if len(data) == 0:
                            break;
                        data = data.split('::')
                        Name = data[1].split('-')[0]
                        StuNum = data[1].split('-')[1]
                        if data[2][0] == "+":
                            Length = int(data[2][1:])
                        else:
                            Length = -1 * int(data[2][1:])
                        Times = int(data[3])

                        # print ("name:%s, stunum:%s, Length:%s, times:%i" %(Name, StuNum, Length, Times))
                        self.Data.emit(Name, StuNum, Length, Times)
                except IOError:
                    print u"连接断开"
                    self.ConnectFlag = False
                    self.IsConnect.emit(False)
            else:
                print("Waiting for connection on RFCOMM channel %d" %self.port)
                self.client_sock, self.client_info = self.server_sock.accept()
                print("Accepted connection from ", self.client_info)
                self.ConnectFlag = True
                self.IsConnect.emit(True)
            

if __name__ == "__main__":
    blue = bluetooth()
    blue.connect()
    blue.run()